<template>
	<layout>
		<div class="wrapper">
			<div class="result-box" @click="sceneImg(imageUrl)" v-if="imageUrl">
				<img :src="imageUrl" alt="点击查看" />
			</div>
			<div class="btn" @click="downloadPdf" v-if="imageUrl && !iphone">
				<img src="../../assets/images/icon_dowmload_w.png">
				<div class="t1">下载高清版PDF报告单</div>
			</div>
      <div class="btn" v-if="imageUrl && iphone">
        <img src="../../assets/images/icon_dowmload_w.png">
        <div class="t1">长按上面图片，保存图片</div>
      </div>
			<div class="tips" v-if="!imageUrl">
				<img src="../../assets/images/icon_empty.png" alt="暂无数据" />
				<div class="t2">暂无数据</div>
			</div>
			<canvas style="display: none" ref="pdfCanvas"></canvas>
		</div>
		<div class="botton-tip">
			下载方式：<br />
			1.长按报告单图片，选择“保存到手机”<br />
			2.点击下载高清版PDF报告单
		</div>
		<div class="botton-tip">
			客服热线：400-1512-686
		</div>
	</layout>
</template>

<script>

import {ImagePreview, Toast} from 'vant';
import { getDocument } from 'pdfjs-dist/build/pdf';
import { GlobalWorkerOptions } from 'pdfjs-dist';
export default {
	name: "reportList",
	components: {},
	data() {
		return {
      imageUrl: '',
      iphone: false,
			pdfUrl: this.$route.query.uri,
			pdfDocument: null,
		}
	},
	mounted() {
		if (this.pdfUrl) {
			Toast.loading({
				message: '加载中...',
				forbidClick: true,
				duration: 0
			});
		}
		// 设置 Worker 路径
		GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js';
		this.loadPDF();

    if (this.isAppleMobileDevice()) {
      //console.log('苹果手机打开H5');
      this.iphone = true;
    } else {
      //console.log('非苹果手机');

    }

	},
	methods: {
    isAppleMobileDevice() {
      const userAgent = navigator.userAgent;
      return /iPad|iPhone|iPod/.test(userAgent) && !window.MSStream;
    },
		async loadPDF() {
			try {
				// 获取 PDF 数据
				const response = await fetch(this.pdfUrl);
				const data = await response.arrayBuffer();
				// 加载 PDF 文档
				this.pdfDocument = await getDocument(new Uint8Array(data)).promise;
				await this.renderPDF();
			} catch (error) {
				console.error('加载 PDF 时出错:', error);
			}
		},
		async renderPDF() {
			const canvas = this.$refs.pdfCanvas;
			const context = canvas.getContext('2d');

			// 获得设备像素比

			// 获取 PDF 页数
			const pageCount = this.pdfDocument.numPages;
			const scale = 5;
			let totalHeight = 0;
			let maxWidth = 0;

			// 首先计算每页的总高度和最大宽度
			for (let pageNum = 1; pageNum <= pageCount; pageNum++) {
				const page = await this.pdfDocument.getPage(pageNum);
				const viewport = page.getViewport({ scale: scale  });
				totalHeight += viewport.height;
				maxWidth = Math.max(maxWidth, viewport.width);
			}

			canvas.width = maxWidth;
			canvas.height = totalHeight;

			// 逐页渲染 PDF 到 Canvas
			let currentHeight = 0;
			for (let pageNum = 1; pageNum <= pageCount; pageNum++) {
				const page = await this.pdfDocument.getPage(pageNum);
				const viewport = page.getViewport({ scale: scale });

				// 计算渲染上下文
				const renderContext = {
					canvasContext: context,
					viewport: viewport,
				};

				// 在 Canvas 上渲染当前页
				await page.render(renderContext).promise;

				// 更新当前绘制高度
				// eslint-disable-next-line no-unused-vars
				currentHeight += viewport.height;

				// 将 Canvas 的上下文向下平移以绘制下一页
				context.translate(0, viewport.height);
			}
			Toast.clear();
			this.imageUrl = canvas.toDataURL('image/png');
		},
		sceneImg(val) {
			let list = [];
			list.push(val);
			// 图片预览
			ImagePreview({
				images: list,
				showIndex: true, //是否显示页码
				loop: false, //是否开启循环播放
				startPosition: 0
			});
		},
    downloadPdf() {
      window.open(this.pdfUrl,"_blank");
    },
		downloadImage() {
			const nowDate = new Date()
			const date = {
				year: nowDate.getFullYear(),
				month: nowDate.getMonth() + 1,
				date: nowDate.getDate(),
				hours: nowDate.getHours(),
				minutes: nowDate.getMinutes(),
				seconds: nowDate.getSeconds()
			}
			const link = document.createElement('a');
			link.href = this.imageUrl;
			link.download = `KR${date.year}${date.month}${date.date}${date.hours}${date.minutes}${date.seconds}.png`; // 设定下载的文件名
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		},

	}
}
</script>
<style lang="less" scoped>
.wrapper {
	font-size: 15px;
	margin: auto;
	// padding: 5px;
	width: 93%;

	.tips {
		img {
			width: 100%;
		}

		.t2 {
			display: flex;
			justify-content: center;
			align-items: center;
			color: #8d8d8d;
			margin-bottom: 1rem;
		}
	}

	.result-box {
		margin-left: 2%;
		margin-right: 2%;
		border: solid #c5c5c5;
		border-width: 0.05rem;

		img {
			width: 100%;
			 height: 5rem;
			object-fit: cover;
		}
	}

	.btn {
		display: flex;
		flex-direction: row;
		align-content: center;
		justify-content: center;
		align-items: center;
		width: 58%;
		margin-left: 20%;
		margin-right: 20%;
		background: white;
		padding: 2%;
		border-radius: 0.3rem;
		margin-top: 0.5rem;
		background: #1989FA;

		img {
			width: 0.6rem;
			height: 0.6rem;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			margin-right: 0.1rem;

		}

		.t1 {
			font-size: 0.4rem;
			color: #fbfbfb;
			// font-weight: bold;
		}
	}
}

.botton-tip {
	width: 93%;
	margin: auto;
	margin-top: 12px;
	font-size: 12px;
	color: red;
	line-height: 24px;
}</style>
